package com.pets.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pets.entity.BountyList;
import com.pets.entity.FileInformation;
import com.pets.entity.Users;
import com.pets.mapper.BountyListMapper;
import com.pets.mapper.FileInformationMapper;
import com.pets.mapper.UsersMapper;
import com.pets.service.IBountyListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pets.utils.Result;
import com.pets.viewModels.BountyListViewModels;
import com.pets.viewModels.FileViewModels;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 悬赏表 服务实现类
 * </p>
 *
 * @author 啦啦啦
 * @since 2024-04-09
 */
@Service
public class BountyListServiceImpl extends ServiceImpl<BountyListMapper, BountyList> implements IBountyListService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private BountyListMapper bountyListMapper;
    @Autowired
    private FileInformationMapper fileInformationMapper;

    /**
     * 创建悬赏
     */
    @Override
    public Result register(BountyList bountyList) {
        if (bountyList.getUserId() == null) {
            return Result.fail("未获取到用户信息，请重新退出登录！");
        }
        Users users = usersMapper.selectById(bountyList.getUserId());
        if(users==null|| users.getIsDisable()){
            return Result.fail("当前用户不存在或已被禁用！");
        }
        if (bountyList.getBountyListIntegral() == null) {
            return Result.fail("未设置积分！");
        }
        if (users.getIntegral() == null||users.getIntegral()==0||bountyList.getBountyListIntegral()>users.getIntegral()) {
            return Result.fail("积分不足，请上传文件获取积分或完成他人悬赏！");
        }
        if (bountyList.getBountyListName() == null || bountyList.getBountyListName().isEmpty()) {
            return Result.fail("未设置悬赏名称！");
        }
        bountyList.setCreateTime(LocalDateTime.now());
        bountyList.setIsItCompleted(false);
        if(bountyListMapper.insert(bountyList) > 0){
            Integer integral = users.getIntegral();
            integral = integral - bountyList.getBountyListIntegral();
            users.setIntegral(integral);
            usersMapper.updateById(users);
            return Result.success("创建成功！");
        }else {
            return Result.fail("创建失败！");
        }
    }

    @Override
    public Result updateData(BountyList bountyList) {
        if (bountyList.getUserId() == null) {
            return Result.fail("未获取到用户信息，请重新退出登录！");
        }
        if (bountyList.getBountyListName() == null || bountyList.getBountyListName().isEmpty()) {
            return Result.fail("未设置悬赏名称！");
        }
        return bountyListMapper.updateById(bountyList) > 0 ? Result.success("修改成功！") : Result.fail("修改失败！");
    }

    @Override
    public Result deleteById(Integer id, Integer userId) {
        if (id == null ||  userId ==null) {
            return Result.fail("未获取到参数！");
        }
        Users users = usersMapper.selectById(userId);
        if (users == null) {
            return Result.fail("登录失效！");
        }
        BountyList bountyList = bountyListMapper.selectById(id);
        if (bountyList == null) {
            return Result.fail("未获取到要删除的悬赏信息！");
        }
        if (users.getIsAdministrators() || bountyList.getUserId() == users.getUserId()) {
            return bountyListMapper.deleteById(id) > 0 ? Result.success("删除成功！") : Result.fail("删除失败！");
        } else {
            return Result.fail("您暂无权限删除他人悬赏！");
        }
    }

    @Override
    public Result selectPage(Integer page, Integer pageSize, String bountyListName, Integer userId) {
        final LambdaQueryWrapper<BountyList> lqw = new LambdaQueryWrapper<>();
        lqw.like(bountyListName != null && !bountyListName.isEmpty(), BountyList::getBountyListName, bountyListName)
                .eq(userId != null, BountyList::getUserId, userId);
        IPage<BountyList> Page = new Page<>(page, pageSize);
        IPage<BountyList> IPage = bountyListMapper.selectPage(Page, lqw);

        //返回模型
        IPage<BountyListViewModels> newIPage = new Page<>();
        newIPage.setPages(IPage.getPages());
        newIPage.setCurrent(IPage.getCurrent());
        newIPage.setSize(IPage.getSize());
        newIPage.setTotal(IPage.getTotal());

        List<BountyList> bountyListList = IPage.getRecords();
        if(bountyListList==null||bountyListList.size()<=0){
            return Result.success("查询成功！",newIPage);
        }
        List<BountyListViewModels> bountyListViewModelsList = new ArrayList<>();
        //对象映射器
        ModelMapper modelMapper = new ModelMapper();
        for (BountyList bountyList : bountyListList) {
            BountyListViewModels bountyListViewModels = modelMapper.map(bountyList, BountyListViewModels.class);
            Users users1 = usersMapper.selectById(bountyList.getUserId());
            if (users1 != null) {
                bountyListViewModels.setUserName(users1.getNickname());
            }
            if (bountyList.getCompleteUser()!=null){
                Users users2 = usersMapper.selectById(bountyList.getCompleteUser());
                if (users2 != null) {
                    bountyListViewModels.setCompleteUserName(users2.getNickname());
                }
            }
            bountyListViewModelsList.add(bountyListViewModels);
        }
        newIPage.setRecords(bountyListViewModelsList);
        return Result.success("查询成功", newIPage);
    }

    /**
     * 采纳文件
     */
    @Override
    public Result complete(Integer fileId) {
        if (fileId == null) {
            return Result.fail("未获取到参数！");
        }
        //查询文件
        FileInformation fileInformation = fileInformationMapper.selectById(fileId);
        Users users = usersMapper.selectById(fileInformation.getUserId());
        if (users == null) {
            return Result.fail("文件用户已注销！");
        }
        if(fileInformation.getBountyListId() == null){
            return Result.fail("文件不是悬赏上传文件！");
        }
        BountyList bountyList = bountyListMapper.selectById(fileInformation.getBountyListId());
        if (bountyList == null) {
            return Result.fail("未获取到悬赏信息！");
        }
        //判断是否已经完成
        if(bountyList.getIsItCompleted()!=null&& bountyList.getIsItCompleted()){
            return Result.fail("悬赏已经完成！");
        }
        //用户添加积分
        Integer integral = users.getIntegral();
        integral+=bountyList.getBountyListIntegral();
        users.setIntegral(integral);
        //设置文件已被采纳
        fileInformation.setIsAdopt(true);
        fileInformationMapper.updateById(fileInformation);
        //完成悬赏
        bountyList.setIsItCompleted(true);
        bountyList.setCompleteUser(users.getUserId());
        if(bountyListMapper.updateById(bountyList) > 0 ){
            if(usersMapper.updateById(users)>0){
                return Result.success("成功！");
            }else {
                return Result.fail("失败！");
            }
        }else {
            return Result.fail("失败！");
        }
    }
}
